package com.sofa.user.service;

import com.sofa.api.PermissionService;
import com.sofa.user.dto.UserRegisterDTO;
import com.sofa.user.entity.User;
import com.sofa.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.seata.spring.annotation.GlobalTransactional;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {

    private final UserMapper userMapper;
    private final PermissionService permissionService;
    private final PasswordEncoder passwordEncoder;
    private final StreamBridge streamBridge;

    @GlobalTransactional
    @Transactional
    public void register(UserRegisterDTO registerDTO) {
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setEmail(registerDTO.getEmail());
        user.setPhone(registerDTO.getPhone());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);

        log.info("New user registered, userId: {}", user.getUserId());

        // Bind default role
        permissionService.bindDefaultRole(user.getUserId());

        // Send registration log message
        String message = "User registered: " + user.getUsername();
        streamBridge.send("sofa-log-topic", MessageBuilder.withPayload(message).build());
        log.info("Sent registration log message for user: {}", user.getUsername());
    }
} 